<template>
  <el-form
      ref="loginRefForm"
      :model="loginForm"
      :rules="rules"
      :label-position="labelPosition"
      :size="size"
      style="max-width: 350px"
  >
    <el-form-item label="账号" prop="userName">
      <el-input type="text" v-model="loginForm.username" placeholder="请输入账号"/>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"/>
    </el-form-item>
    <div style="width: 100%" class="myFlex-x">
      <el-form-item>
        <el-button type="primary" @click="submitForm">立即登录</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request.ts";
import {useUserStore} from "@/stores/useUserStore.ts";

const userStore = useUserStore();
// 接受父组件传来的函数
const emit = defineEmits(['close-dialog']);

let loginRefForm = ref();
const size = ref('large');
const labelPosition = ref('left');
let loginForm = ref({
  username:"",
  password:""
})
const rules={
  username:[
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{5,12}$/,message: '账号必须是数字和字母组成，长度是5，12位',trigger: "blur"}
  ],
  password:[
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{5,12}$/,message: '密码必须是数字和字母组成，长度是5，12',trigger: "blur"}
  ]
}
// 点击重置
function resetForm (){
  loginRefForm.value.resetFields()
}
// 点击登录
function submitForm(){
  loginRefForm.value.validate(async valid => {
    if (valid){
      request.get("/login",{params:loginForm.value})
          .then(res=>{
            if (res.data!=null){
              ElMessage.success("登录成功")
              emit("close-dialog")
              // 登录成功后，将用户的信息保存到用户状态中，状态组件是pinia组件
              userStore.$patch({
                userName:res.data.username,
                id:res.data.id
              })
            }else {
              ElMessage.error("登录失败")
            }
          })// 访问后端成功后的回调函数
          .catch(err=>{
            ElMessage.error(err.message);
          })// 响应失败的回调函数
    }else {
      ElMessage.error('登录失败')
    }
  })
}
</script>

<style scoped>

</style>